package com.bs.demo.interceptor;

import com.alibaba.fastjson.JSON;
import com.bs.common.constant.RequestHeaderConstant;
import com.bs.common.vo.LoginUserVo;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bingshao
 * @date 2022/9/21
 **/
public class DemoRestInterceptor extends HandlerInterceptorAdapter {

    public static final ThreadLocal<LoginUserVo> loginUserThreadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userString = request.getHeader(RequestHeaderConstant.USER);
        LoginUserVo loginUserVo = JSON.parseObject(userString, LoginUserVo.class);
        loginUserThreadLocal.set(loginUserVo);
//        Enumeration<String> headerNames = request.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String header = headerNames.nextElement();
//            System.out.println("header=====>" + header);
//        }
        // HandlerInterceptorAdapter不适合进行参数的加密解密
        // 获取post请求体但是会和@RequestBody冲突，因为request.getReader()和request.getInputStream()一次请求只能调用一次，@RequestBody本质也是调用request.getInputStream()
//        String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
//        System.out.println("body===========>" + body);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        loginUserThreadLocal.remove();
    }

}
